<template>
  <div style="width: 100%; margin-bottom: 15px" v-loading="loading">
    <div class="top-bar">
      <div class="item" style="margin-top: 10px">
        <el-tooltip class="item" effect="dark" content="重新加载数据" placement="top">
          <a href="#" @click="getData"><i class="el-icon-refresh"></i></a>
        </el-tooltip>
      </div>
      <div class="item">
        <el-date-picker
            v-model="dateRange"
            size="small"
            style="width: 245px;height: 40px;"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="getData"/>
      </div>
      <div class="item" style="margin-top: 10px">
        <el-checkbox v-model="queryAll" label="全部报警" @change="getData"/>
      </div>
    </div>
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="alarmType" label="报警类型" width="180"/>
      <el-table-column prop="equipmentCode" label="设备组" width="200">
        <template slot-scope="scope">{{ getGroupName(scope.row.equipmentCode) }}</template>
      </el-table-column>
      <el-table-column prop="equipmentCode" label="报警设备" width="180">
        <template slot-scope="scope">{{ getEquipName(scope.row.equipmentCode) }}</template>
      </el-table-column>
      <el-table-column prop="alarmTime" label="报警时间" width="180">
        <template slot-scope="scope">{{ parseTime(scope.row.alarmTime) }}</template>
      </el-table-column>
      <el-table-column prop="alarmContent" label="报警内容" :show-overflow-tooltip="true"/>
      <el-table-column fixed="right" label="操作" width="80">
        <template slot-scope="scope">
          <el-button @click="handleDetail(scope.row)" type="text" size="small" icon="el-icon-s-operation">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getData"
    />

    <el-dialog title="报警详情" :visible.sync="open" :close-on-click-modal="false" :show-close="false" width="700px" append-to-body>
      <div class="chart-wrapper">
        <el-card class="box-card">
          <div slot="header" class="clearfix" v-if="false">
            <span>报警详情</span>
            <el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button>
          </div>
          <el-form label-width="100px" label-position="left" v-if="alarm">
            <el-row>
              <el-col :span="12">
                <el-form-item label="报警类型">{{ alarm.alarmType }}</el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="报警时间">{{ parseTime(alarm.alarmTime) }}</el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="设备组">{{ getGroupName(alarm.equipmentCode) }}</el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="报警设备">{{ getEquipName(alarm.equipmentCode) }}</el-form-item>
              </el-col>
              <el-col :span="12" v-if="false">
                <el-form-item label="部件名称">{{ alarm.componentCode }}</el-form-item>
              </el-col>
              <el-col :span="12" v-if="false">
                <el-form-item label="部件劣化区域">{{ alarm.componentArea }}</el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="报警内容">{{ alarm.alarmContent }}</el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="维修建议">{{ alarm.repairSuggestion }}</el-form-item>
              </el-col>
              <el-col :span="24" v-if="alarm.alarmReason">
                <el-form-item label="报警原因">
                  <span v-for="(item,index) in alarm.alarmReason" :key="index" style="display: block">{{ item }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="24" v-if="alarm.alarmType==='自适应阈值报警'">
                <el-form-item label="报警报告">
                  <el-button v-if="!hasReport" :disabled="disabled" type="primary" size="small" icon="el-icon-document" @click="handleGenerate(alarm)">生成报告</el-button>
                  <el-button v-if="hasReport" type="primary" size="small" icon="el-icon-download" @click="handleExport(alarm)">下载报告</el-button>
                  <el-button v-if="hasReport" type="danger" size="small" icon="el-icon-delete" @click="handleDelete(alarm)">删除报告</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </div>
      <div class="bottom_wrap">
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Pagination from "@/components/Pagination/index.vue";
import {queryAlarm} from "@/api/diag";
import {parseTime} from "@/utils/common";
import {check, deleteFile, generate} from "@/api/alarm";

export default {
  name: "alarmTable",
  components: {Pagination},
  props: ['selectedEquip', "equipList"],
  data() {
    return {
      loading: false,
      total: 0,
      tableData: [],
      queryAll: false,
      dateRange: [],
      queryParams: {
        equipmentCode: null,
        pageNum: 1,
        pageSize: 10
      },
      open: false,
      alarm: null,
      hasReport: false,
      disabled: false,
      checkInterval: null  //存储定时器ID
    }
  },
  watch: {
    selectedEquip: {
      handler: function (val) {
        this.$nextTick(() => {
          this.queryAll = false;
          this.dateRange = [];
          this.getData();
        })
      },
      immediate: true
    }
  },
  mounted() {
    // this.total = 1;
    // this.tableData = [
    //   {
    //     "alarmContent": "根据设定阈值，设备运行在明显劣化区域，其中None测点的vel_x方向振动强度最大",
    //     "alarmReason": [
    //       "时域：测点名称 None 通道 vel_z 健康区域 明显劣化",
    //       "频域：测点名称 None 通道 acc_z 失效模式 定子失效"
    //     ],
    //     "alarmTime": "2025-04-09 12:30:45",
    //     "alarmType": "自适应阈值报警",
    //     "componentArea": 3,
    //     "componentCode": "stator",
    //     "componentType": 3,
    //     "deviceCode": null,
    //     "equipmentCode": "ZHTJJGCF00010001ANMO0001B1G",
    //     "pointCode": "ZHTJJGCF00010001ANMO00010001ROLB884",
    //     "repairSuggestion": "关注设备运行状态，进行备件准备"
    //   }
    // ]
  },
  methods: {
    parseTime,
    getData() {
      if (this.queryAll) {
        this.queryParams.equipmentCode = null
      } else {
        this.queryParams.equipmentCode = this.selectedEquip[this.selectedEquip.length - 1];
      }
      this.total = 0;
      this.tableData = [];
      let query = this.addDateRange(this.queryParams, this.dateRange);
      queryAlarm(query).then(res => {
        this.total = res.total;
        this.tableData = res.rows;
      })
    },
    handleDetail(row) {
      this.open = true;
      this.alarm = row;
      this.checkReport(row)
    },
    cancel() {
      this.open = false;
    },
    getEquipName(equipCode) {
      let find = this.equipList.find(item => item.equipmentCode === equipCode);
      return find ? find.equipmentName : null;
    },
    getGroupName(equipCode) {
      let find1 = this.equipList.find(item => item.equipmentCode === equipCode);
      if (!find1) return null;
      let find2 = this.equipList.find(item => item.equipmentId === find1.parentId);
      if (!find2) return null;
      let find3 = this.equipList.find(item => item.equipmentId === find2.parentId);
      return find3 ? find3.equipmentName + "-" + find2.equipmentName : null;
    },
    checkReport(alarm) {
      // 先清除已有定时器（避免重复创建）
      if (this.checkInterval) {
        clearInterval(this.checkInterval);
      }
      // 立即检查一次
      this.doCheck(alarm);

      // 设置定时检查（每5秒检查一次）
      this.checkInterval = setInterval(() => {
        this.doCheck(alarm);
      }, 5000);
    },
    doCheck(alarm) {
      check(alarm.equipmentCode, alarm.alarmTime).then(res => {
        this.hasReport = res.data;
        if (this.hasReport) {
          clearInterval(this.checkInterval);
          this.checkInterval = null;
          this.disabled = false;
          console.log('检测到报告存在，已停止定时检查');
        }
      }).catch(err => {
        console.error('检查报告出错:', err);
      });
    },
    handleGenerate(row) {
      if (!this.getEquipName(row.equipmentCode)) {
        this.$message.error("设备信息不存在，无法生成报告。");
        return;
      }
      this.disabled = true;
      generate(row).then(res => {
        this.$message.success("报告生成中，请稍后查看结果。");
      })
    },
    handleExport(alarm) {
      this.download('alarm/export', {
        ...alarm
      }, `alarm_${alarm.equipmentCode}_${alarm.alarmTime}_${new Date().getTime()}.docx`)
    },
    handleDelete(row) {
      this.disabled = true;
      this.$modal.confirm('是否确认删除"' + row.equipmentCode + '"报告文档？').then(function() {
        return deleteFile(row);
      }).then(() => {
        this.checkReport(row);
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    }
  },
  beforeDestroy() {
    // 组件销毁前清除定时器
    if (this.checkInterval) {
      clearInterval(this.checkInterval);
    }
  }
}
</script>

<style scoped>
.top-bar {
  margin-bottom: 20px !important;
  display: flex;
}

.top-bar > .item {
  margin: 0 0 0 10px;
}

.bottom_wrap {
  margin-top: 10px;
  text-align: right;
}
</style>